package com.lnsf.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.lnsf.dao.IShopDao;
import com.lnsf.dbutils.DataAccess;
import com.lnsf.model.Shop;

public class ShopDaoImpl implements IShopDao {

	@Override
	public List<Shop> select() {
		List<Shop> list = new ArrayList<Shop>();
		Connection conn = null;
		PreparedStatement prep = null;
		ResultSet rs = null;
		try {
			conn = DataAccess.getConnection();
			prep = conn.prepareStatement("select * from shop");
			rs = prep.executeQuery();
			while (rs.next()) {
				Shop shop = new Shop(rs.getInt(1), rs.getString(2), rs.getString(3), rs.getInt(4));
				list.add(shop);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DataAccess.closeConnection(rs, prep, conn);
		}
		return list;
	}

	@Override
	public int insert(Shop shop) {
		int flag = 0;
		Connection conn = null;
		PreparedStatement prep = null;
		try {
			conn = DataAccess.getConnection();
			prep = conn.prepareStatement("insert into shop values (null, ?, ?, ?)");
			prep.setString(1, shop.getsName());
			prep.setString(2, shop.getStatus());
			prep.setInt(3, shop.getuId());
			prep.execute();
			flag = 1;
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DataAccess.closeConnection(prep, conn);
		}
		return flag;
	}

	@Override
	public int update(Shop shop) {
		int flag = 0;
		Connection conn = null;
		PreparedStatement prep = null;
		try {
			conn = DataAccess.getConnection();
			prep = conn.prepareStatement("update shop set sName = ? ,status=?,uId=? where shId = ?");
			prep.setString(1, shop.getsName());
			prep.setString(2, shop.getStatus());
			prep.setInt(3, shop.getuId());
			prep.setInt(4, shop.getShId());
			prep.execute();
			flag = 1;
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DataAccess.closeConnection(prep, conn);
		}
		return flag;
	}

	@Override
	public int delete(Shop shop) {
		int flag = 0;
		Connection conn = null;
		PreparedStatement prep = null;
		try {
			conn = DataAccess.getConnection();
			prep = conn.prepareStatement("delete from shop where shId = ?");
			prep.setInt(1, shop.getShId());
			prep.execute();
			flag = 1;
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DataAccess.closeConnection(prep, conn);
		}
		return flag;
	}
}
